//
// Created by admin on 25-6-12.
//

#ifndef IMAGEVIEW_H
#define IMAGEVIEW_H


#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsPixmapItem>
#include <QFileDialog>
#include <QWheelEvent>
#include <QMouseEvent>
#include <QSettings>

class ImageView : public QGraphicsView
{
private:
    QString lastDirectory;

public:
    ImageView(QWidget* parent = nullptr) : QGraphicsView(parent)
    {
        scene = new QGraphicsScene(this);
        setScene(scene);

        // 设置渲染质量
        setRenderHint(QPainter::Antialiasing);
        setRenderHint(QPainter::SmoothPixmapTransform);

        // 设置变换锚点
        setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
        setResizeAnchor(QGraphicsView::AnchorUnderMouse);

        // 设置背景
        setBackgroundBrush(QBrush(QColor(240, 240, 240)));

        // 启用鼠标跟踪（用于鼠标悬停效果）
        setMouseTracking(true);

        // 初始化拖拽状态
        isPanning = false;
        lastPanPoint = QPoint();
    }

    void loadImage(const QString& filePath)
    {
        QPixmap pixmap(filePath);
        if (pixmap.isNull())
        {
            return;
        }

        // 清除现有图片
        scene->clear();

        // 添加图片到场景
        QGraphicsPixmapItem* item = scene->addPixmap(pixmap);
        item->setPos(0, 0);

        // 调整视图以适应图片
        fitInView(scene->itemsBoundingRect(), Qt::KeepAspectRatio);
    }

    void loadPicture()
    {
        // 从 QSettings 加载上次路径（如果有）
        if (lastDirectory.isEmpty())
        {
            QSettings settings("ft", "IMG");
            lastDirectory = settings.value("lastImageDir", QDir::homePath()).toString();
        }

        // 打开文件对话框，传入上次路径
        const QString filePath = QFileDialog::getOpenFileName(
            this, "Open Image", lastDirectory,
            "Image Files (*.png *.jpg *.jpeg *.bmp *.gif)"
        );

        if (!filePath.isEmpty())
        {
            // 更新上次路径
            lastDirectory = QFileInfo(filePath).absolutePath();
            // 保存到 QSettings
            QSettings settings("FT", "IMG");
            settings.setValue("lastImageDir", lastDirectory);
            // 加载图片...
            loadImage(filePath);
        }
    }

protected:
    // 鼠标按下事件 - 开始拖拽
    void mousePressEvent(QMouseEvent* event) override
    {
        if (event->button() == Qt::LeftButton)
        {
            // 保存当前鼠标位置
            lastPanPoint = event->pos();

            // 切换到拖拽模式
            isPanning = true;

            // 更改鼠标光标为手型
            setCursor(Qt::ClosedHandCursor);
        }

        // 调用父类的鼠标按下事件处理
        QGraphicsView::mousePressEvent(event);
    }

    // 鼠标释放事件 - 结束拖拽
    void mouseReleaseEvent(QMouseEvent* event) override
    {
        if (event->button() == Qt::LeftButton)
        {
            // 结束拖拽模式
            isPanning = false;

            // 恢复默认光标
            setCursor(Qt::ArrowCursor);
        }

        // 调用父类的鼠标释放事件处理
        QGraphicsView::mouseReleaseEvent(event);
    }

    // 鼠标移动事件 - 执行拖拽
    void mouseMoveEvent(QMouseEvent* event) override
    {
        if (isPanning)
        {
            // 计算鼠标移动的距离
            QPointF delta = mapToScene(lastPanPoint) - mapToScene(event->pos());

            // 更新最后鼠标位置
            lastPanPoint = event->pos();

            // 平移视图
            translate(delta.x(), delta.y());
        }

        // 调用父类的鼠标移动事件处理
        QGraphicsView::mouseMoveEvent(event);
    }

    // 滚轮事件 - 实现缩放
    void wheelEvent(QWheelEvent* event) override
    {
        const ViewportAnchor anchor = transformationAnchor();
        setTransformationAnchor(AnchorUnderMouse);

        double scaleFactor = 1.15;
        if (event->angleDelta().y() < 0)
        {
            scaleFactor = 1.0 / scaleFactor; // 缩小
        }

        scale(scaleFactor, scaleFactor);
        setTransformationAnchor(anchor);
    }

private:
    QGraphicsScene* scene;
    bool isPanning; // 是否处于拖拽状态
    QPoint lastPanPoint; // 上次鼠标位置
};


#endif //IMAGEVIEW_H
